<?php

namespace IDock\Insurance\MACN\Request;

use Exception;
use IDock\Insurance\MACN\MACNEnums;
use IDock\Insurance\MACN\Response\UnderwritingResponse;
use IDock\Visitor\Premium\PremiumInquiryVisitor;
use IDock\Visitor\Premium\PremiumUnderwritingVisitor;
use IDock\Visitor\SpecialClausesVisitor;

/**
 * 核保接口
 */
class UnderwritingRequest extends AllMACNRequest
{
    public $requestType = '0021';

    protected $response = UnderwritingResponse::class;

    protected $urlTip = '核保';

    public $queryType;

    public $queryDetail;

    public $flag;

    public $engageFlag = '0';


    /**
     * @var PremiumInquiryVisitor $visitor
     */
    protected $visitor;

    /**
     * @return array
     * @throws Exception
     */
    public function generate(): array
    {
        $data = [
            'baseInfo' => [
                'askCalcNo' => $this->visitor->getExtInfoVisitor()->argc['askCalcNo'] ?? '',
                'queryType' => $this->queryType,
                'queryDetail' => $this->queryDetail,
                'flag' => $this->flag,
            ],
            'policyInfo' => $this->getPolicyInfo(),
            'holderInfo' => $this->getHolderInfo(),
            'insuredInfo' => $this->getInsuredInfo(),
            'carOwnerInfo' => $this->getCarOwnerInfo(),
            'agentComm' => $this->getAgentInfo(),
            'engages' => $this->getEngageList()
        ];
        //取消文件上传 放在外面单独上传
        //$files = $this->visitor->getFileList();
        //
        //if(!empty($files)){
        //    $data['imageUpload'] = ['fileList' => ['fileInfo' => $this->getFileList()]];
        //}
        return $data;
    }

    private function getFileList()
    {
        $files = $this->visitor->getFileList();
        $imageList = [];
        foreach ($files as $file){
            $extArr = explode('.',$file['url']);
            $ext = end($extArr);
            if($ext == 'jpeg'){
                $ext = 'jpg';
            }
            if(!in_array($ext,['png','jpg','mp4'])){
                throw new Exception("仅支持png和jpg");
            }
            $imageList[] = [
                'base64' => base64_encode(file_get_contents($file['url'])),
                'documentType' => MACNEnums::$uploadFileType[$file['type']],
//                'url' => $file['url'],
                'urlType' => $ext,//后缀名
            ];
        }
        return $imageList;
    }

    private function getPolicyInfo()
    {
        return [
            'companyCode' => $this->visitor->getExtInfoVisitor()->argc['companyCode'] ?? '',
            'operatorCode' => $this->visitor->getExtInfoVisitor()->argc['operatorCode'] ?? '',
            'electFlag' => true,
            'paperFlag' => false,
            'engageFlag' => $this->engageFlag,
        ];
    }

    private function getHolderInfo()
    {
        $holder = $this->visitor->getApplicantVisitor();
        $arr = [
            'personType' => $holder->typeCode == 'R1' ? '1' : '2',
            'personName' => $holder->name,
            'identifyType' => MACNEnums::$certificateTypeCode[$holder->certificateTypeCode],
            'identifyNumber' => $holder->certificateNo,
            'address' => $holder->address,
            'mobilePhone' => $holder->mobile,
            'email' => $holder->email,
            'carRelation' => '1',
            'clientLevel' => '1',
            'insuredNature' => $holder->typeCode == 'R1' ? '1' : '2',
            'insuredType' => $holder->typeCode == 'R1' ? '3' : '4',
            'unitType' => '',
            'idCardStartDate' => $holder->certificateStartDate,
            'idCardEndDate' => $holder->certificateEndDate,
        ];
        if($holder->typeCode == 'R1'){
            $arr['birthDate'] = $this->getBirthday($holder->certificateNo);
            $arr['sex'] = $this->getGenderByIdCard($holder->certificateNo);
            $arr['age'] = $this->getAgeFromIdCard($holder->certificateNo);
        }
        if (empty($arr['identifyType'])) {
            throw new Exception("不支持该投保人证件类型");
        }
        if ($arr['personType'] == 2) {
//            $arr['unitType'] = MACNEnums::$organizationType[$holder->organizationType];
            $arr['unitType'] = '56';//默认其他
            if (empty($arr['unitType'])) {
                throw new Exception("不支持该投保人单位性质");
            }
        }
        return $arr;
    }

    public function getAgeFromIdCard($idCard) {
        if (strlen($idCard) != 18) {
            return false; // 身份证号码必须是18位
        }
        $birthYear = substr($idCard, 6, 4); // 获取出生年份
        $currentYear = date("Y"); // 获取当前年份
        return $currentYear - $birthYear; // 计算年龄
    }

    private function getInsuredInfo()
    {
        $insured = $this->visitor->getInsuredVisitor();
        $arr = [
            'personType' => $insured->typeCode == 'R1' ? '1' : '2',
            'personName' => $insured->name,
            'identifyType' => MACNEnums::$certificateTypeCode[$insured->certificateTypeCode],
            'identifyNumber' => $insured->certificateNo,
            'address' => $insured->address,
            'mobilePhone' => $insured->mobile,
            'email' => $insured->email,
            'carRelation' => '1',
            'clientLevel' => '1',
            'insuredNature' => $insured->typeCode == 'R1' ? '1' : '2',
            'insuredType' => $insured->typeCode == 'R1' ? '3' : '4',
            'unitType' => '',
            'idCardStartDate' => $insured->certificateStartDate,
            'idCardEndDate' => $insured->certificateEndDate,
        ];
        if($insured->typeCode == 'R1'){
            $arr['birthDate'] = $this->getBirthday($insured->certificateNo);
            $arr['sex'] = $this->getGenderByIdCard($insured->certificateNo);
            $arr['age'] = $this->getAgeFromIdCard($insured->certificateNo);
        }
        if (empty($arr['identifyType'])) {
            throw new Exception("不支持该被保人证件类型");
        }
        if ($arr['personType'] == 2) {
//            $arr['unitType'] = MACNEnums::$organizationType[$insured->organizationType];
            $arr['unitType'] = '56';//默认其他
            if (empty($arr['unitType'])) {
                throw new Exception("不支持该被保人单位性质");
            }
        }
        return $arr;
    }

    private function getCarOwnerInfo()
    {
        $owner = $this->visitor->getOwnerVisitor();
        $arr = [
            'personType' => $owner->typeCode == 'R1' ? '1' : '2',
            'personName' => $owner->name,
            'identifyType' => MACNEnums::$certificateTypeCode[$owner->certificateTypeCode],
            'identifyNumber' => $owner->certificateNo,
            'address' => $owner->address,
            'mobilePhone' => $owner->mobile,
            'email' => $owner->email,
            'carRelation' => '1',
            'clientLevel' => '1',//固定
            'insuredNature' => $owner->typeCode == 'R1' ? '1' : '2',
            'insuredType' => $owner->typeCode == 'R1' ? '3' : '4',
            'unitType' => '',
            'idCardStartDate' => $owner->certificateStartDate,
            'idCardEndDate' => $owner->certificateEndDate,
        ];
        if($owner->typeCode == 'R1'){
            $arr['birthDate'] = $this->getBirthday($owner->certificateNo);
            $arr['sex'] = $this->getGenderByIdCard($owner->certificateNo);
            $arr['age'] = $this->getAgeFromIdCard($owner->certificateNo);
        }
        if (empty($arr['identifyType'])) {
            throw new Exception("不支持该车主证件类型");
        }
        if ($arr['personType'] == 2) {
//            $arr['unitType'] = MACNEnums::$organizationType[$owner->organizationType];
            $arr['unitType'] = '56';//默认其他
            if (empty($arr['unitType'])) {
                throw new Exception("不支持该车主单位性质");
            }
        }
        return $arr;
    }

    private function getAgentInfo()
    {
        $arr = [
            'businessNature' => '20101',//渠道类型 固定20101
            'agencyCode' => $this->visitor->getExtInfoVisitor()->argc['subAgrtNo'] ?? '',//子协议号
            'agencyName' => $this->visitor->getExtInfoVisitor()->argc['agencyName'] ?? '',//代理名称
            'agreementNO' => $this->visitor->getExtInfoVisitor()->argc['agrtNo'] ?? '',//协议号
            'crperiod' => '30',//账期 固定30
            'certificateNo' => $this->visitor->getExtInfoVisitor()->argc['certificateNo'] ?? '',//许可证号
            'solutionCode' => $this->visitor->getExtInfoVisitor()->argc['solutionCode'] ?? '',//分配方案
            'salePeopleName' => $this->visitor->getExtInfoVisitor()->argc['salePeopleName'] ?? '',//中介销售人名字
            'salePeopleRegisterNo' => $this->visitor->getExtInfoVisitor()->argc['salePeopleRegisterNo'] ?? '',//中介销售人职业证号
            'partnerId' => '',//推修厂编码
            'partnerName' => '',//推修厂名称
        ];
        return $arr;
    }

    private function getEngageList()
    {
        $list = [];
        $engageList = $this->visitor->getUnderwritingVisitor()->specialClausesList;
        /**@var SpecialClausesVisitor $val */
        foreach ($engageList as $val){
            $list[] = [
                'clauseNo' => $val->clauseCode
            ];
        }
        return $list;
    }

    /**
     * 通过身份证获取性别
     * @param $idCard
     * @return int
     * @throws Exception
     */
    private function getGenderByIdCard($idCard)
    {
        if (strlen($idCard) != 18) {
            throw new Exception("身份证位数不合法");
        }
        $gender = intval(substr($idCard, 16, 1)) % 2;
        return $gender ? '1' : '0';
    }

    /**
     * 通过身份证获取生日
     * @param $idCard
     * @return string
     * @throws Exception
     */
    private function getBirthday($idCard)
    {
        if (strlen($idCard) != 18) {
            throw new Exception("身份证位数不合法");
        }
        return substr($idCard, 6, 4) . '-' . substr($idCard, 10, 2) . '-' . substr($idCard, 12, 2);
    }
}
